package br.com.sgs.view;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

/**
 *
 * @author eric.santos
 */
public class Pagination extends PdfPageEventHelper {  
  
      
    protected PdfTemplate total;       
    protected BaseFont helv;  
    private PdfPTable page;
    
    public Pagination(){
        
        page = new PdfPTable(1);
        page.setTotalWidth(150);
        page.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        page.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
        page.getDefaultCell().setBorder(0);
        
    }
      
    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
       
        total = writer.getDirectContent().createTemplate(100, 100);
        total.setBoundingBox(new Rectangle(-20, -20, 100, 100));
        try {
            helv = BaseFont.createFont(BaseFont.TIMES_ROMAN,
                    BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }
      
    @Override
    public void onEndPage(PdfWriter writer, Document document) {

        //Page Number code
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        String text = "folha " + writer.getPageNumber() + "/";
        float textBase = document.bottom() - 22;
        float textSize = helv.getWidthPoint(text, 10);
        float adjust = helv.getWidthPoint("0", 12);
        cb.beginText();
        cb.setFontAndSize(helv, 10);
        cb.setTextMatrix(document.right() - textSize - adjust, textBase);
        cb.showText(text);
        cb.endText();
        cb.addTemplate(total, document.right() - adjust, textBase);
        cb.restoreState();
        /*    * End of page number code       */
    }

     public void onCloseDocument(PdfWriter writer, Document document) {
      
        total.beginText();
        total.setFontAndSize(helv, 10);
        total.setTextMatrix(0, 0);
        total.showText(String.valueOf(writer.getPageNumber() - 1));
        total.endText();
    }

    /**
     * @return the page
     */
    public PdfPTable getPage() {
        return page;
    }

    /**
     * @param page the page to set
     */
    public void setPage(PdfPTable page) {
        this.page = page;
    }

}
